import React, { useState, useContext, useEffect } from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import { EffectCoverflow } from 'swiper/modules'
import { LayoutContext } from '@/pages/layouts/context'
import SwiperContent from './SwiperContent'

import 'swiper/css'
import 'swiper/css/effect-coverflow'
import './index.scss'

const Swipers = () => {
  const { activePlan, planInfos } = useContext(LayoutContext)
  const [datas, setDatas] = useState([])
  const [key, setKey] = useState(0)

  useEffect(() => {
    setKey(Math.random() * 1000) // 刷新组件
    if (!planInfos) return
    let d = [...planInfos]
    d.length < 6 && (d = d.concat(d)) // 数量小于6个样式会有问题，拼一下
    setDatas(d)
  }, [activePlan, planInfos])

  return (
    <div className="PlanStart-Swiper">
      <Swiper
        key={key}
        loop={true}
        effect={'coverflow'}
        grabCursor={true}
        centeredSlides={true}
        slidesPerView={3}
        initialSlide={planInfos?.findIndex(
          (item) => item.plan_id === activePlan.plan_id
        )}
        height={'80%'}
        coverflowEffect={{
          rotate: 50,
          stretch: -80,
          depth: 200,
          modifier: 1,
          slideShadows: true
        }}
        modules={[EffectCoverflow]}
        className="mySwiper"
      >
        {planInfos
          ? datas.map((item, idx) => {
              return (
                <SwiperSlide key={idx}>
                  <SwiperContent data={item}></SwiperContent>
                </SwiperSlide>
              )
            })
          : []}
      </Swiper>
    </div>
  )
}

export default Swipers
